/*
 * ConfigLoader.cpp
 *
 *  Created on: Sep 30, 2010
 *      Author: gabriel
 */

#include "ConfigLoader.h"

namespace Utility
{
	ConfigLoader::ConfigLoader()	{}

	ConfigLoader::~ConfigLoader()	{}

	int ConfigLoader::loadFile( std::string fileToLoad )
	{
		cfgFileName = fileToLoad;

		std::ifstream dataLink;
		std::string buffer;
		char buffLine[1024];

		dataLink.open( cfgFileName.c_str() );
		if ( !dataLink )
			return FILE_READ_ERROR;

		while ( dataLink.getline( buffLine , 1024 ) )
		{
			if ( buffLine[0] != ';' )
			{
				buffer = buffLine;

				size_t equal_pos = buffer.find ( "=" );
				size_t equal_pos_s = equal_pos + 1;

				try
				{
					cfgFileMap[buffer.substr( 0 , equal_pos ).c_str()] = buffer.substr( equal_pos_s ).c_str();
				}
				catch ( std::exception e )	{}
			}
		}
		dataLink.close();

		return DONE;
	}

	ConfigRet ConfigLoader::getConf( std::string index )
	{
		ConfigRet ret;

		if ( ConfigLoader::findInMap( index.c_str() ) )
			ret.data = cfgFileMap[index.c_str()];
		else
			ret.data = "null";

		return ret;
	}

	bool ConfigLoader::findInMap ( std::string index )
	{
		ConfigLoaderMap::iterator iter = cfgFileMap.find( index.c_str() );
		if ( iter != cfgFileMap.end() )
			return true;
		else
			return false;
	}

	int ConfigRet::toint ()
	{
		try
		{
			return std::atoi ( data.c_str() );
		}
		catch ( std::exception e )
		{
			return 0;
		}
	};

	float ConfigRet::tofloat ()
	{
		try
		{
			return std::atof ( data.c_str() );
		}
		catch ( std::exception e )
		{
			return 0;
		}
	}

	long ConfigRet::tolong ()
	{
		try
		{
			return std::atol ( data.c_str() );
		}
		catch ( std::exception e )
		{
			return 0;
		}
	}

	std::string ConfigRet::tostring ()
	{
		return data.c_str();
	}
}
